package cn.iocoder.yudao.module.promotion.gift.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.module.api.promotion.gift.GiftActivityApi;
import cn.iocoder.yudao.module.api.promotion.gift.GiftScanConfigApi;
import cn.iocoder.yudao.module.api.promotion.gift.dto.GiftActivityVO;
import cn.iocoder.yudao.module.promotion.gift.service.app.AppGiftActivityService;
import cn.iocoder.yudao.module.promotion.gift.service.core.CoreGiftScanConfigService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <pre>
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 *  这里是文件说明
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * </pre>
 *
 * @author 山野羡民（1032694760@qq.com）
 * @since 2025/05/27
 */
@Slf4j
@Service
@Validated
public class GiftScanConfigApiImpl implements GiftScanConfigApi {
    @Resource
    private CoreGiftScanConfigService coreGiftScanConfigService;
    @Resource
    private AppGiftActivityService appGiftActivityService;

    @Resource
    private GiftActivityApi giftActivityApi;

    @Override
    public List<GiftActivityVO> getGiftActivities(Long userId, Long shopId, Integer price) {
        List<Long> giftActivityIds = coreGiftScanConfigService.getGiftActivityIds(shopId, price);
        if (CollUtil.isEmpty(giftActivityIds)) {
            return List.of();
        }
        List<GiftActivityVO> list = appGiftActivityService.getList(giftActivityIds);
        Set<Long> giftActivityIdsSet = list.stream()
                .filter(it -> Boolean.TRUE.equals(it.getValid()))
                .map(GiftActivityVO::getId)
                .collect(Collectors.toSet());
        Map<Long, Integer> countMap = giftActivityApi.countReceived(userId, giftActivityIdsSet);
        log.debug("giftActivity countMap: {}", JSONUtil.toJsonStr(countMap));
        for (GiftActivityVO vo : list) {
            vo.setTakeReceivedCount(countMap.getOrDefault(vo.getId(), 0));
        }
        return list;
    }

}
